#include "ConfigMgr.h"

ConfigMgr::ConfigMgr()
{
    
    //使用boost::property_tree库从config.ini文件中读取配置
    boost::property_tree::ptree pt;
    //执行到下面这行代码就报错了，提示config.ini文件不存在
        //解决方法：在GateServer目录下执行./GateServer，而不是在src目录下执行
    boost::property_tree::read_ini("../config.ini",pt);

    //遍历配置文件中的所有section
    for(const auto &section :pt)
    {
        const std::string & section_name = section.first;
        const boost::property_tree::ptree & section_tree = section.second;

        std::map<std::string,std::string> section_datas;
        //对于每个section，遍历其所有的kv对，然后将kv对放入_section_datas中
        for(const auto &kv : section_tree)
        {
            const std::string & key = kv.first;
            const std::string & value = kv.second.get_value<std::string>();
            section_datas[key] = value;
        }
        SectionInfo section_info;
        section_info.section_datas_ = section_datas;
        config_map_[section_name] = section_info;
    }

    //打印所有的配置项
    for(const auto &section:config_map_)
    {
        const std::string& section_name = section.first;
        const SectionInfo& section_info = section.second;
         std::cout<<section_name<<":"<<"\n";
        for(const auto& kvpair:section_info.section_datas_)
        {
            
           std::cout<<kvpair.first<<":"<<kvpair.second<<"\n";
        }
        std::cout<<"\n";
    }

}
ConfigMgr::~ConfigMgr()
{
    config_map_.clear();
    std::cout<<"ConfigMgr::~ConfigMgr()"<<std::endl;
}

std::string ConfigMgr::GetValue(const std::string &sectionName,const std::string&key)
{
    if(config_map_.find(sectionName)==config_map_.end())
    {
        return "";
    }
    SectionInfo& section_info = config_map_[sectionName];
    if(section_info.section_datas_.find(key)==section_info.section_datas_.end())
    {
        return "";
    }
    return section_info.section_datas_[key];
    
}